#pragma once

#include <iostream>
#include <functional>
#include <cstdio>

class Task
{
    using func_t = std::function<void(int)>;

public:
    Task() {}

    Task(int sock, func_t callback)
        : _sock(sock), _callback(callback)
    {
    }

    std::string operator()()
    {
        _callback(_sock); // 跳转到上层传入的函数的位置
    }

    ~Task() {}

private:
    int _sock;
    std::string _name;
    func_t _callback; // 回调方法
};

void serverIO(int socket)
{
    char buffer[1024];
    while (true)
    {
        ssize_t n = read(socket, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "recv message# " << buffer << std::endl;

            std::string outbuffer = buffer;
            outbuffer += " [server return]";
            // 将收到的消息返回给客户端
            write(socket, outbuffer.c_str(), outbuffer.size());
        }
        else if (n == 0)
        {
            // 读到0，代表客户端退出
            logMessage(NORMAL, "client quit, me too");
            break;
        }
    }
    close(socket);
}